package splash.core.security;

import java.io.File;
import java.io.IOException;
import java.io.FileNotFoundException;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class UserLoader
{
	
	private UserList ul;
	
	private static final String USERNAME = "ime";
	private static final String PASSWORD = "geslo";
	private static final String RESTRICTION = "omejitev";
	
	/* Onemogocimo konstruktor  */
	protected UserLoader()
	{
	}
	
	public static UserList loadUsers(String fname) throws FileNotFoundException, CorruptedFileException
	{
		File f;
		Document doc = null; 
		
		try
		{
			f = new File(fname);
			if(!f.exists())
				throw new FileNotFoundException("Datoteka " + fname + " ne obstaja.");
			
			doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(f);
		}
		catch(SAXException e)
		{
			throw new CorruptedFileException("Slaba xml datoteka");
		}
		catch(IOException e)
		{
			e.printStackTrace();
		}
		catch(ParserConfigurationException e)
		{
			e.printStackTrace();
		}

		
		UserList ul = new UserList();
		
		NodeList n = doc.getChildNodes().item(0).getChildNodes();
		for(int i = 0; i < n.getLength(); i++)
		{
			if(n.item(i).getTextContent().matches("\\s*"))
				continue;
			if(n.item(i).getNodeName().equals("user"))
			{
				NodeList userdata = n.item(i).getChildNodes();
				String[] user = new String[2];
				RestrictionSet rs = new RestrictionSet();
				
				for(int j = 0; j < userdata.getLength(); j++)
				{
					if(userdata.item(j).getNodeName().equals(USERNAME))
						user[0] = userdata.item(j).getTextContent();
					else if(userdata.item(j).getNodeName().equals(PASSWORD))
						user[1] = userdata.item(j).getTextContent();
					else if(userdata.item(j).getNodeName().equals(RESTRICTION))
						rs.add(new Restriction(userdata.item(j).getTextContent()));
					else
						continue;
				}
				
				if(user[0] == null || user[1] == null)
					throw new CorruptedFileException("Slaba xml datoteka.");
				
				//preveri omejitve.
				rs.check();
				//
				ul.add(new User(user[0],user[1], rs, true));
			}
		}
		
		return ul;
	
	}
}
